//
//  CollectionView.swift
//  Wmsmobile
//
//  Created by wangshuning on 16/8/25.
//  Copyright © 2016年 www.hd123.com. All rights reserved.
//

import UIKit

import SVProgressHUD
import MJRefresh
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return l < r
  case (nil, _?):
    return true
  default:
    return false
  }
}

fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return l > r
  default:
    return rhs < lhs
  }
}


class FavoriteView: UICollectionView,UICollectionViewDelegateFlowLayout ,UICollectionViewDataSource , UICollectionViewDelegate {
    
    //MARK: - property
    var dataArray: [YunCangModel]?{
        didSet{
            if dataArray?.count > 0 {
                defaultImage.isHidden = true
            }else{
                defaultImage.isHidden = false
            }
            reloadData()
        }
    }
    var layout: UICollectionViewFlowLayout?
    lazy fileprivate var defaultImage:UIImageView = {
        let imageView = UIImageView(image: UIImage(named: "favorites_empty"))
        return imageView
    }()

    init(){
        let flowLayout = UICollectionViewFlowLayout()
        super.init(frame: CGRect(x: 0, y: 0, width: KscreenWidth, height: KscreenHeight), collectionViewLayout: flowLayout)
        self.register(YunCangViewCellCollectionViewCell.self, forCellWithReuseIdentifier: "favoriteCell")
        self.alwaysBounceVertical = true
        flowLayout.minimumLineSpacing = CellSpaceMainmenu
        flowLayout.minimumInteritemSpacing = CellSpaceMainmenu
        NotificationCenter.default.addObserver(self, selector: #selector(FavoriteView.datasourceChanged(_:)), name: NSNotification.Name(rawValue: "favoriteItemsChanged"), object: nil)//注册通知，接受数据源的变化
        self.delegate = self
        self.dataSource = self
        self.addSubview(defaultImage)
        self.backgroundColor = UIColor.hexStringToUIColor("#dddddd")
        //布局子view
        defaultImage.snp.makeConstraints { (make) in
            make.centerX.equalTo(self)
            make.centerY.equalTo(self).offset(-120)
        }
        let header = MJRefreshNormalHeader(refreshingBlock: {
            NetworkTool.sharedTools.postSoap(["piOperator" : (userInfo?.userName)!], bodyMethod: "GetUserUsedModule", suffix: "225", success: { (data) in
                let numberArray = analysisManager.shareManager.XmlParserAnalysis(XMLParser(data: data), elementName: "collect")
                var modelArray = [YunCangModel]()
                for item in (userInfo?.mainMenuDataArray)! {
                    for model in item {
                        for value in numberArray{
                            if String(validatingUTF8: model.FMODULENO!)! == value["模块号"]{
                                modelArray.append(model)
                            }
                        }
                    }
                }
                //得到了新的数组
                userInfo?.favoriteItems = modelArray
                self.dataArray = modelArray
            self.mj_header.endRefreshing()
            }, failed: {
                SVProgressHUD.showError(withStatus: "刷新失败")
              self.mj_header.endRefreshing()
           })
        })
        header?.setTitle("正在刷新", for: MJRefreshState.refreshing)
        header?.setTitle("下拉开始刷新", for: MJRefreshState.idle)
        header?.setTitle("松开开始刷新", for: MJRefreshState.pulling)
        header?.lastUpdatedTimeLabel.isHidden = true
        self.mj_header = header
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: - lifeCycle
    override func willMove(toWindow newWindow: UIWindow?) {
   
    }
    //MARK: - private
    func datasourceChanged(_ notification: Notification){
        self.dataArray = userInfo?.favoriteItems
    }
    
    //MARK: - collectionDatasource
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if let rows = self.dataArray?.count {
            let column = userInfo?.fontLevel == .large ? 3 : 4
            if rows % column == 0{
                return rows
            }
            return rows + (column - rows % column)
        }
        return self.dataArray?.count ?? 0
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let model:YunCangModel? = (self.dataArray?.count)!  < (indexPath as NSIndexPath).row + 1 ? nil : (self.dataArray?[(indexPath as NSIndexPath).item])
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "favoriteCell", for: indexPath) as! YunCangViewCellCollectionViewCell
        cell.model = model
        return cell
    }
    //MARK: - collectionViewDelegate
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let column:CGFloat = userInfo?.fontLevel == .large ? 3 : 4
        let columnd:CGFloat = column - 1 //代表列数 -1
        let width:CGFloat = ((KscreenWidth - columnd * CellSpaceMainmenu) - (KscreenWidth - columnd * CellSpaceMainmenu).truncatingRemainder(dividingBy: (CellSpaceMainmenu * column))) / column
        if (indexPath as NSIndexPath).row % Int(column) == 2 {
            let newWidth = collectionView.contentSize.width - columnd * (width + CellSpaceMainmenu)
            return CGSize(width: newWidth, height: width)
        }
        return CGSize(width: width, height: width)
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        self.deselectItem(at: indexPath, animated: true)
        if (indexPath as NSIndexPath).row + 1 > self.dataArray!.count {
            return
        }
        let model:YunCangModel = self.dataArray![(indexPath as NSIndexPath).row]
        let VCName = (model.FCLASSNAME?.replacingOccurrences(of: ".", with: "_"))! + "Controller"
        if let VCClassTemp = stringClassFromStringOptional(VCName){
            if let VCClass = VCClassTemp as? UITableViewController.Type {
                let vc = VCClass.init()
                self.parentController()?.navigationController?.pushViewController(vc, animated: true)
                return
            }
        }
//        if let dataArrayName = model.FCAPTION{
//            let path = Bundle.main.path(forResource: "controllersData.plist", ofType: nil)
//            if NSDictionary(contentsOfFile:(path)!)![dataArrayName] != nil{
//                let vc = ContainerPickController(info: NSDictionary(contentsOfFile:(path)!)![dataArrayName] , model: model)
//                vc.title = dataArrayName
//                self.parentController()?.navigationController?.pushViewController(vc, animated: true)
//            }
//        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
//        let remind:CGFloat = userInfo?.fontLevel == .large ? 1.5 : 2
//        switch (KscreenWidth - remind + 0.5) % remind {
//        case 0:
//            return UIEdgeInsetsMake(0.5, 0, 0.5, 0)
//        case 0.5:
//            return UIEdgeInsetsMake(0.5, 0.5, 0.5, 0)
//        case 1:
//            return UIEdgeInsetsMake(0.5, 0.5, 0.5, 0.5)
//        case 1.5:
//            return UIEdgeInsetsMake(0.5, 1, 0.5, 0.5)
//        default:
            return UIEdgeInsetsMake(CellSpaceMainmenu, 0, CellSpaceMainmenu, 0)
//        }

    }

   }
